import { defineStore } from 'pinia';
import { ref } from 'vue';

interface AuthRoute {
	[key: string]: any;
}

export const useAuthStore = defineStore(
	'auth',
	() => {
		const authRoutes = ref<AuthRoute[]>([]);
		const flatAuthRoutes = ref<AuthRoute[]>([]);

		const setAuthRoutes = (routes: AuthRoute[]) => {
			authRoutes.value = routes;
			flatRoutes(routes);
		};

		const flatRoutes = (routes: AuthRoute[]) => {
			const result: AuthRoute[] = [];
			const flatten = (items: AuthRoute[]) => {
				items.forEach((item) => {
					result.push(item);
					if (item.children && item.children.length > 0) {
						flatten(item.children);
					}
				});
			};
			flatten(routes);
			flatAuthRoutes.value = result;
		};

		return {
			authRoutes,
			flatAuthRoutes,
			setAuthRoutes,
		};
	},
	{
		persist: {
			storage: sessionStorage,
		},
	}
);
